package edu.university.demo.core.file;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.commons.CommonsFileUploadSupport;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

public class MyCommonsMultipartResolver extends CommonsMultipartResolver {
	
	protected CommonsFileUploadSupport.MultipartParsingResult parseRequest(HttpServletRequest request)throws MultipartException{
	    String encoding = determineEncoding(request);
	    FileUpload fileUpload = this.prepareFileUpload(encoding,request);
			try {
				List fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
				return parseFileItems(fileItems, encoding);
				
			} catch (FileUploadBase.SizeLimitExceededException ex) {
				throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(),
						ex);
			} catch (FileUploadException ex) {
				throw new MultipartException(
						"Could not parse multipart servlet request", ex);
			}
	   
	  }
		
		protected FileUpload prepareFileUpload(String encoding,HttpServletRequest request) {
			FileUpload fileUpload = getFileUpload();
			FileUpload actualFileUpload = fileUpload;
			// Use new temporary FileUpload instance if the request specifies
			// its own encoding that does not match the default encoding.
			if (encoding != null && !encoding.equals(fileUpload.getHeaderEncoding())) {
				actualFileUpload = newFileUpload(getFileItemFactory());
				actualFileUpload.setHeaderEncoding(encoding);
			}
			
			String requestURI = request.getRequestURI();
			boolean isImage = requestURI.contains("/song/upload/img");
			boolean isMp3 = requestURI.contains("/song/upload/mp3");
			boolean isLyr = requestURI.contains("/song/upload/lyr");
			//如果是上传图片,则上传文件的大小限制为3m
			if(isImage){	
				actualFileUpload.setSizeMax(1024 * 1024 * 3);
				//如果是上传mp3歌曲,则上传文件的大小限制为50m
			}else if(isMp3){
				actualFileUpload.setSizeMax(1024 * 1024 * 50);
				//如果是上次歌词,则上传文件的大小限制为1m
			}else if(isLyr) {
				actualFileUpload.setSizeMax(1024 * 1024 * 1);
			}else {
				actualFileUpload.setSizeMax(1024 * 1024 * 10);
			}
			return actualFileUpload;
		}

	}
